﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using System.Data;
using System.IO;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Reflection;
using System.ComponentModel;
using NPOI.XWPF.UserModel;

namespace CSharp.Infrastructure
{
    public class WordHelper : IDisposable
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public WordHelper()
        {
        }

        /// <summary>
        /// 获取.docx文件内容，使用NPOI.XWPF插件解析
        /// </summary>
        /// <param name="strFilePath">文件路径</param>
        /// <returns></returns>
        public static string ReadWordContent(byte[] data)
        {
            //读取文本文件流
            StringBuilder content = new StringBuilder();
            using (MemoryStream stream = new MemoryStream(data))
            {
                try
                {
                    //根据提供的文件，创建一个Word文档对象
                    XWPFDocument docx = new XWPFDocument(stream);

                    //获取Word文档的所有段落对象
                    IList<XWPFParagraph> paragraphs = docx.Paragraphs;
                    //……
                    foreach (var item in paragraphs)
                    {
                        content.Append(item.ParagraphText);
                    }

                    return content.ToString();
                }
                catch (Exception e)
                {
                    return "读文档异常:" + e.Message;
                }
            }
        }

        /// <summary>
        /// 重写Dispose方法
        /// </summary>
        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
    }
}
